﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using thailandProject.ViewModel;
using System.Text.RegularExpressions;

namespace thailandProject.Models
{
  public class htmlConverter
  {
    public static String Convert(String text)
    {
      String rt = "";

      try
      {
          rt = text.Replace(Environment.NewLine, "<br />");
          rt = text.Replace("\n", "<br />");
          rt = rt.Replace("   ", "&nbsp; &nbsp; &nbsp;");
          string regex = @"((www\.|(http|https|ftp|news|file)+\:\/\/)[&#95;.a-z0-9-]+\.[a-z0-9\/&#95;:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
          Regex r = new Regex(regex, RegexOptions.IgnoreCase);
          rt = r.Replace(rt, "<a href=\"$1\" title=\"Click to open in a new window or tab\" target=\"&#95;blank\">$1</a>").Replace("href=\"www", "href=\"http://www");

          //Replace the signature
            Dictionary<string, DescPair> tc = EmailTemplateModel.getTagClound();
          DescPair dp;
          tc.TryGetValue("[signature]", out dp);

          rt = rt.Replace("[signature]", dp.defaultValue);

          tc.TryGetValue("[paypal]", out dp);
          rt = rt.Replace("[paypal]", dp.defaultValue);

          HttpRequestWrapper Request = new HttpRequestWrapper(HttpContext.Current.Request);
          rt = rt.Replace("../../", "http://" + Request.Url.Authority + "/");

      }
      catch (Exception ex)
      {
          ErrorLog.logError(ex);
      }

      return rt;
    }

    public static String ConvertForDB(String text)
    {
        string rt = Convert(text);

        rt = rt.Replace("฿", "&#" + (int)'฿' + ";"); 

        return rt;
    }
  }
}